/**
 * Created by kevin on 16/8/16.
 */

var eosi = window.eosi || {};
this.eosi.fotile = this.eosi.fotile || {};

var $location=(function () {
    this.searchs = {};
    var arr = window.location.href.split('?');
    if (arr.length > 1) {
        arr = arr[1].split('#')[0].split('&');
        for (var i=0; i<arr.length; ++i) {
            var _arr = arr[i].split('=');
            this.searchs[_arr[0]] = _arr[1];
        }
    }
    return searchs;
})(window);
//Fotile.SERSION = "201608221335";
var version = "201608221335";
var canvas;
var targetWidth;//页面宽度高度
var targetHeight;//页面宽度高度
var stage;
var DEBUG = true;
var fpsLabel;
var browserInfo;
var hengpingInfo;
var alertText;
var shuping;//是竖屏
var isMaster = true;//是否是主机的判断
var master = null;//主机实例
var loadingMessageField = null;
var displayMessage = null;
var resLoader =null;//资源加载器
var resIsLoaded = false;//必要资源加载完毕
var isMute = false;
var soundSwitcher = null;//音乐开关

function prepare(){
    console.log('I am Fitile!!');
    /*if (createjs.BrowserDetect.isIOS) {
        console.log('IOS');
    }
    else if (createjs.BrowserDetect.isAndroid) {
        console.log('android');
    }else{
        console.log('other');
    }*/

    this.canvas = document.getElementById("canvas");
    //console.log(this.canvas.getContext("2d"));
    this.targetWidth = this.getWidth();
    this.targetHeight = this.getHeight();

    //alert(targetWidth);
    this.canvas.width=this.targetWidth;
    this.canvas.height=this.targetHeight;


    this.stage = new createjs.Stage(canvas);
    this.stage.autoClear = true;
    this.container = new createjs.Container();

    this.stage.addEventListener("stagemousedown", handleTouch,false,true);
    this.stage.addChild(this.container);



    //if (createjs.BrowserDetect.isIOS || createjs.BrowserDetect.isAndroid || createjs.BrowserDetect.isBlackberry || createjs.BrowserDetect.isWindowPhone) {
        //document.addEventListener("click", handleTouch, false);	// works on Android, does not work on iOS
        	// works on Android and iPad
        //displayMessage.innerHTML = "Touch to Start";
    //}
    //console.log( this.container.getBounds.height);

    function handleTouch(evt){
        this.stage.removeEventListener("stagemousedown", handleTouch);
        //console.log(evt)
        this.setMessage("");
        if(this.resIsLoaded){
            this.init();
        }else{
            console.log("资源还没有加载完毕")
        }

    }



    //content.regX = 140;
    //content.regY = 140;
    //content.visible = false;
    //console.log(this.DEBUG)
    if(this.DEBUG){
        this.fpsLabel = new createjs.Text("-- fps", "bold 14px Arial", "#000000");
        //stage.addChildAt(fpsLabel,1000);
        this.stage.addChild(this.fpsLabel);
        this.fpsLabel.x = 10;
        this.fpsLabel.y = this.getHeight()-20;

        this.browserInfo = new createjs.Text(detect.viewportWidth()+"x"+detect.viewportHeight(), "bold 14px Arial", "#000000");
        //this.browserInfo = new createjs.Text(this.targetWidth+"x"+this.targetHeight, "bold 14px Arial", "#000000");
        this.stage.addChild(this.browserInfo);
        this.browserInfo.x = 100;
        this.browserInfo.y = this.getHeight()-20;
    }


    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", this.hengshuping, false);
    if (!createjs.Ticker.hasEventListener("tick")) {
        createjs.Ticker.timingMode = createjs.Ticker.RAF;
        createjs.Ticker.addEventListener("tick", this.tick);
    }
    if(this.loadingMessageField == null){
        this.loadingMessageField = new createjs.Text("loading...", "bold 20px Arial", "#000000");
        this.loadingMessageField.maxWidth = 200;
        this.loadingMessageField.textAlign = "right";
        this.loadingMessageField.textBaseline = "middle";
        this.loadingMessageField.x = this.canvas.width ;
        this.loadingMessageField.y = 20;//canvas.height / 2;
        this.stage.addChild(this.loadingMessageField);
        //console.log( this.loadingMessageField);
    }

    if(this.isMaster){
        this.setMessage("Loading resoures...");
        this.loadRes();
    }
}



function init() {
    // var load=[
    //     {src:"static/master/index/bg.jpg",id:"bg"},
    //     {src:"static/master/index/bg_bottom.png",id:"bg_bottom"},
    //     {src:"static/master/index/bird.png",id:"bird"},
    //     {src:"static/master/index/bird1.png",id:"bird1"},
    //     {src:"static/master/index/bird2.png",id:"bird2"},
    //     {src:"static/master/index/bird3.png",id:"bird3"},
    //     {src:"static/master/index/cloud1.png",id:"cloud1"},
    //     {src:"static/master/index/cloud2.png",id:"cloud2"},
    //     {src:"static/master/index/items.png",id:"items"},
    //     {src:"static/master/index/text_box_bg.png",id:"text_box_bg"},
    //     {src:"static/master/index/logo.png",id:"logo"},
    //     {src:"static/master/text/a_1.png",id:"a_1"},
    //     {src:"static/master/text/a_2.png",id:"a_2"},
    //     {src:"static/master/text/a_3.png",id:"a_3"},
    //     {src:"static/master/text/a_4.png",id:"a_4"},
    //     {src:"static/master/text/a_5.png",id:"a_5"},
    //     {src:"static/master/text/a_6.png",id:"a_6"},
    //     {src:"static/master/downarrow.png",id:"downarrow"},
    //     {src:"js/Fotileindex.js",id:"Fotileindex"},];
    if(this.isMaster){
        // master = new eosi.fotile.Fotileloader(this,load,function(){
        //     container.removeChild(master);
        //     master.clearLoading();//清空loadingUI
        //     indexpage = new eosi.fotile.Fotileindex(this);
        //     container.addChild(indexpage);
        // },0);
        if ($location.rid) {
            // master = new eosi.fotile.Fotilewait(this);
            // master = new eosi.fotile.Fotilewait_join(this);
            // master = new eosi.fotile.Fotilewait_play(this);
            // master = new eosi.fotile.Fotileintro(this);
            master = new eosi.fotile.Fotiletextafter(this);
        }else{
            master = new eosi.fotile.Fotileindex(this);
        }
        container.addChild(master);
        master.addEventListener('added',masterAdded);
    }
}

function masterAdded(evt){
    master.removeEventListener('added',masterAdded);
    // master.loadMasterUIRes();
}

//显示信息
function setMessage(message){
    if(this.displayMessage == null){
        this.displayMessage =  new createjs.Text(message, "50px Arial", "#ff7700");
        this.displayMessage.x = (this.targetWidth - this.displayMessage.getBounds().width)/2;
        this.displayMessage.y = (this.targetHeight - this.displayMessage.getBounds().height)/2;
        this.stage.addChild(this.displayMessage);
    }
    this.displayMessage.text = message;
        //this.displayMessage.visible=false;

}

//加载资源
function loadRes(){
    var fotile = this;
    var manifest = [
        {src:"js/FotileMaster.js",id:"FotileMaster"},
        {src:"js/Fotileloader.js",id:"Fotileloader"},
        {src:"js/Fotileindex.js",id:"Fotileindex"}, 
        {src:"js/Fotilewait_join.js",id:"Fotilewait_join"}, 
        {src:"js/Fotilewait_play.js",id:"Fotilewait_play"},
        {src:"js/Fotiletextafter.js",id:"Fotiletextafter"},
        {src:"js/Fotileintro.js",id:"Fotileintro"}, 
        {src:"static/public/UI.png",id:"public_UI"},
        {src:"lib/tweenjs-0.6.1.min.js",id:"tweenjs"},
        {src:"lib/soundjs-NEXT.min.js",id:"soundjs"},
        {src:"static/master/loading/loading.png",id:"loading"},
        {src:"static/master/loading/loading_bg.png",id:"loading_bg"},
    ];
    resLoader = new createjs.LoadQueue(true);
    resLoader.on("error", resLoadError);
    resLoader.on("complete", resLoadComplete);
    resLoader.on("progress", updateLoading,true);
    resLoader.loadManifest(manifest, true, "./_assets/");
    //加载完毕
    function resLoadComplete(event){
        fotile.setMessage("Touch me to start");
        console.log("res loaded");
        fotile.resIsLoaded = true;
        fotile.drawUI();
        //console.log(fotile);
    }

    //文件加载失败
    function resLoadError(event) {
        console.log("res文件加载失败："+event.target);
    }
}
//绘制UI
function drawUI(){
    console.log("drawUI");
    var UI_ss = new createjs.SpriteSheet({
        framerate: 24,
        "images": [resLoader.getResult("public_UI")],
        frames: [
            // x, y, width, height, imageIndex*, regX*, regY*
            [0, 0, 46, 79,0,23,40],
            [50, 0, 52, 79,0,26,40]
            //[412, 730, 298, 419,0]
        ],
        "animations": {
            //开始， 结束， 下一个， 速度
            "sound_switcher_on": [0,0],
            "sound_switcher_off": [1,1]
        }
    });
    soundSwitcher = new createjs.MovieClip(null, 0, true, {on:0});
    soundSwitcher.x=50
    soundSwitcher.y=50
    soundSwitcher.scaleX=soundSwitcher.scaleY = .5;
    this.stage.addChild(soundSwitcher);
    var hit_area = new createjs.Shape();
    //hit_area.graphics.beginFill("#ffffff").drawRect(-75, -75, 150, 150);
    hit_area.graphics.beginFill("#ffffff").drawCircle(0,0,75);
    hit_area.alpha=.2;

    soundSwitcher.addChild(hit_area);

    soundSwitcher.addEventListener("mousedown",clickSound);

    var soundSwitcher_on_1 = new createjs.Sprite(UI_ss,"sound_switcher_on");
    var soundSwitcher_on_2 = new createjs.Sprite(UI_ss,"sound_switcher_on");
    var soundSwitcher_on_3 = new createjs.Sprite(UI_ss,"sound_switcher_on");
    soundSwitcher_on_1.visible = !this.isMute;
    soundSwitcher_on_2.visible = !this.isMute;
    soundSwitcher_on_3.visible = !this.isMute;
    soundSwitcher.timeline.addTween(
        createjs.Tween.get(soundSwitcher_on_1)
            //.to({rotation: 0}).to({rotation: 20},20).to({rotation: 0},20).to({rotation: -20},20).to({rotation: 0},20));
            .to({rotation: 0}));
    soundSwitcher.timeline.addTween(
        createjs.Tween.get(soundSwitcher_on_2)
            .to({rotation: 0,x:0,y:0,scaleX:1,scalex:1,alpha:1}).to({rotation: 80,x:20,y:-100,scaleX:.1,scaleY:.1,alpha:0}, 80));
    soundSwitcher.timeline.addTween(
        createjs.Tween.get(soundSwitcher_on_3)
            .wait(50)
            .to({rotation: 0,x:0,y:0,scaleX:1,scalex:1,alpha:1}).to({rotation: -80,x:-50,y:-100,scaleX:.1,scaleY:.1,alpha:0}, 120));
    //soundSwitcher.addChild(soundSwitcher_on);
    //console.log(soundSwitcher.getBounds());
    //soundSwitcher.gotoAndStop("on");
    var soundSwitcher_off = new createjs.Sprite(UI_ss,"sound_switcher_off");
    soundSwitcher_off.alpha = 0.5;
    soundSwitcher_off.visible = this.isMute;
    soundSwitcher.addChild(soundSwitcher_off);
    function clickSound(evt){
        //this.isMute=!this.isMute;
        this.switchSound();
        soundSwitcher_off.visible = this.isMute;
        soundSwitcher_on_1.visible = !this.isMute;
        soundSwitcher_on_2.visible = !this.isMute;
        soundSwitcher_on_3.visible = !this.isMute;
        //soundSwitcher.gotoAndStop("off");
        //console.log(soundSwitcher_off);
    }

}



//获取屏幕宽度
function getWidth() {
    var xWidth = null;
    if (window.innerWidth !== null) {
        xWidth = window.innerWidth;
    } else {
        xWidth = document.body.clientWidth;
    }

    return xWidth;
}

//获取屏幕高度
function getHeight () {
    var xHeight = null;
    if (window.innerHeight !== null) {
        xHeight = window.innerHeight;
    } else {
        xHeight = document.body.clientHeight;
    }
    return xHeight;
}

//判断手机横竖屏状态：
function hengshuping(evt){

    if(window.orientation==180||window.orientation==0){
        this.shuping = true;
        //this.fotileAPP.hideScreenTips();
        //console.log(hideScreenTips)
    }
    if(window.orientation==90||window.orientation==-90){
        this.shuping = false;
        //this.fotileAPP.showHideScreenTips();
    }
    //console.log(this.fotileAPP);
    this.showHideScreenTips();
}
//横屏提示
function showHideScreenTips (){
    //console.log(this.shuping);
    //alert(hengpingInfo);
    if(this.shuping){
        //console.log("竖")
        //console.log(this.hengpingInfo);
        if(this.hengpingInfo!=null){
            this.stage.removeChild(this.hengpingInfo);
            this.hengpingInfo = null;
        }

        if(this.alertText!=null){
            this.stage.removeChild(this.alertText);
            this.alertText = null;
        }
        //console.log(this.hengpingInfo);

    }else{
        //console.log("横")
        this.hengpingInfo = new createjs.Shape();
        this.hengpingInfo.graphics.clear().beginFill("#333333").drawRect(0,0,this.targetWidth,this.targetHeight);
        this.stage.addChild(this.hengpingInfo);
        this.alertText = new createjs.Text("请锁屏观看", "25px Arial", "#ffffff");
        this.alertText.x = (this.getWidth()-this.alertText.getMeasuredWidth())/2;
        this.alertText.y = (this.getHeight()-this.alertText.getMeasuredHeight())/2;
        this.stage.addChild(this.alertText);
    }
    this.stage.update();


}


//加载状态更新
function updateLoading (loader) {
    //console.log(this);
    //console.log(loader.target);
    var msg="Loading ";
    //alert(loader.target);
    /*if(loader.target==videoPreloader){
     msg="Loading video ";
     }else if(loader.target == animation_Loader){

     msg="Loading animation ";
     }else if(loader.target == master_UILoader){
     msg="Loading master res ";
     }*/
    //console.log(this.fotileAPP.loadingMessageField);
    //if(loader.target == this.fotileAPP.master.master_UILoader) {
    //    msg = "Loading master res ";
    //}
    //console.log(loadingMessageField)
    if(loader == null){
        loadingMessageField.text = "Nothing is loading!!";
    }else{
        loadingMessageField.text = msg + (loader.progress * 100 | 0) + "%";
    }
    stage.update();
}
//clear loading message
function clearLoading (){
    if(this.loadingMessageField != null){
        this.stage.removeChild(this.loadingMessageField);
        this.loadingMessageField = null;
        this.stage.update();
    }
}

function tick (event) {
    //console.log(event);
    if (this.DEBUG) {
        this.fpsLabel.text = Math.round(createjs.Ticker.getMeasuredFPS()) + " fps";

    }
    // draw the updates to stage
    if (master) {

        // master.tick(event);
    }
    this.stage.update(event);
}

//声音开关
function switchSound(){
    this.isMute=!this.isMute;
    createjs.Sound.muted = this.isMute;
    return this.isMute
}


